package znbkTestPaperRdqh.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import lancooControl.AndroidBug5497Workaround;
import lancooControl.Control;
import lancooControl.NoFastClickUtils;
import lancooControl.PopupWindowMoreFunction;
import znbkChangeCollection.ChangeCollectionEntityModel;
import znbkChangeCollection.ChangeCollectionPresenter.ChangeCollectionPresenter;
import znbkDialog.ZnbkDialogNoAssessSubmit;
import znbkDialog.ZnbkDialogSubmit;
import znbkListRdqh.entity.WeekAscensionListEntity;

import com.example.lancooznbk.MyApplication;
import com.example.lancooznbk.R;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.EmptyMainLayout;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.reviewsystem.utils.ToastUtils;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import znbkListSc.ZnbkPaperScInfor;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperRdqh.ZnbkPaperRdqhInfor;
import znbkTestPaperRdqh.entity.WeekAscensionPaperEntity;
import znbkTestPaperRdqh.fragmentAdapter.WeekAscensionPaperFragmentAdapter;
import znbkTestPaperRdqh.presenter.WeekAscensionPaperPresenter;
import znbkTestPaperRdqh.saveRdqhPaper.SaveWeekAscensionPaperEntity;
import znbkTestPaperRdqh.saveRdqhPaper.SaveWeekAscensionPaperEntityModel;
import znbkTestPaperRdqh.saveRdqhPaper.SaveWeekAscensionPaperPresenter;
import znbkTestPaperXtfx.AnswerSheet;
import znbkTestPaperXtfx.saveDiagnosticReportInfo.SaveDiagnosticReportEntity;
import znbkTestPaperXtfx.saveDiagnosticReportInfo.SaveDiagnosticReportEntityModel;
import znbkTestPaperXtfx.saveDiagnosticReportInfo.SaveDiagnosticReportPresenter;

/**
 * Created by Administrator on 2018\4\2 0002.
 */

public class WeekAscensionPaperActivity extends BaseActivity implements View.OnLayoutChangeListener,
        ILoadPaperView<WeekAscensionPaperEntity>{

    private ScaleButton mSbtnBack;
    private ScaleButton mSbtnAnswerSheet;//答题号菜单
    public static ScaleButton mSbtnSubmit;//提交菜单
    private ScaleButton mSbtnMore;//更多功能菜单
    private ScaleButton mSbtnTimeMeter;//计时器

    public static ViewPager mVp;
    private WeekAscensionPaperFragmentAdapter mAdapter;


    private AnswerSheet mAnswerSheet;

    public static int lastBigViewPage =0;
    public static int currentBigViewPage = 0;

    private WeekAscensionPaperPresenter mPaperPresenter;
    public static WeekAscensionPaperEntity mEntityRdqh;

    //Activity最外层的Layout视图
    private View activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    private WeekAscensionListEntity.ModelPaperInfoListBean mEntity;
    public static final  String PAPER_ENTITY = "paperEntity";
    public static final String PAPER_FROM = "paperFrom";
    public int mQuesOrPaperFrom;
    private LoadingDialog mLoadingDialog;
    private boolean IsSubmitSuccess = false;

    public  static void launch(BaseActivity activity, WeekAscensionListEntity.ModelPaperInfoListBean entity, @ZnbkPaperDef.PaperFrom int quesOrPaperFrom){

        ZnbkPaperRdqhInfor.PaperId = entity.getPaperID();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesOrPaperFrom);
        Intent intent = new Intent(activity, WeekAscensionPaperActivity.class);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent,1);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.activity_test_paper;
    }

    @Override
    protected void initViews() {
        Log.e("====10101======", "==initViews==");
        AndroidBug5497Workaround.assistActivity(this);
        mPaperPresenter = new WeekAscensionPaperPresenter(this,ZnbkPaperDef.FROM_WEEK_ASCENSION);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mEntity = (WeekAscensionListEntity.ModelPaperInfoListBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        currentBigViewPage = 0;

        initView();

        activityRootView = findViewById(R.id.main);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mPaperPresenter.getData(isRefresh);
    }

    /*
    * 开启计时定时器
    * */
    private  int paperTimeLong = 0;
    private int  LastTimer = 0;//记前一次时长
    private int recLen = 0;//当前时长
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            recLen++;
            mSbtnTimeMeter.setText(getStringTime(LastTimer+recLen));
            paperTimeLong = LastTimer+recLen;
            handler.postDelayed(this, 1000);
        }
    };

    private String getStringTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        if(hour>0){
            return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second);
        }else{
            return String.format(Locale.CHINA,"%02d:%02d",min,second);
        }
    }



    /*
    * 初始化界面控件
    * */
    private void initView(){

        mEmptyViewLayout = (EmptyMainLayout) findViewById(R.id.layout_loading);
        /*
        * 返回按钮菜单相关设置
        * */
        mSbtnBack = (ScaleButton) findViewById(R.id.sbtn_back);
        mSbtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdqh!=null) {
                    if (mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState() != 3) {
                        saveAndSubmitPaper(false, false);
                    }else{
                        finish();
                    }
                    HideKeyboard();
                    MyApplication.destoryActivity("1");
                }
            }
        });

        /*
        * 答题号按钮菜单相关信息
        * */
        mSbtnAnswerSheet = (ScaleButton) findViewById(R.id.sbtn_answerSheet);
        mSbtnAnswerSheet.setVisibility(View.INVISIBLE);
        mSbtnAnswerSheet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdqh!=null) {
                    if (NoFastClickUtils.isFastClick()) {
                        //快速点击后的逻辑，可以提示用户点击太快，休息一会
                        Toast.makeText(getApplicationContext(), "点击太快，休息一会", Toast.LENGTH_SHORT).show();

                    } else {
                        //正常点击的逻辑
                        Fragment fragment = (Fragment) ((WeekAscensionPaperFragmentAdapter) mVp.getAdapter()).instantiateItem(mVp,mVp.getCurrentItem());
                        ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
                        mAnswerSheet = new AnswerSheet(WeekAscensionPaperActivity.this,mVp.getCurrentItem(),childViewPage.getCurrentItem(),ZnbkPaperDef.FROM_WEEK_ASCENSION);
                        mAnswerSheet.setClippingEnabled(false);//使popupwindow显示为全屏
                        mAnswerSheet.showAtLocation(WeekAscensionPaperActivity.this.findViewById(R.id.main), Gravity.TOP, 0, 0);
                    }
                }else{
                    Toast.makeText(getApplicationContext(), "数据加载中，请稍后重试...", Toast.LENGTH_SHORT).show();
                }

            }
        });

        /*
        * 提交按钮菜单相关信息
        * */
        mSbtnSubmit = (ScaleButton) findViewById(R.id.sbtn_submit);
        mSbtnSubmit.setVisibility(View.INVISIBLE);
        mSbtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState()!=3){
                    //执行提交操作
                    boolean IsNeedAssess = false;
                    int sumTotalItemCount =  mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getTotalItemCount();
                    for(int i=0;i<sumTotalItemCount;i++){
                        int childeAnswerType = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().get(0).getChildAnswerType();
                        if(childeAnswerType==4){
                            IsNeedAssess = true;
                            break;
                        }
                    }

                    if(IsNeedAssess) {
                        dialogAssessSubmit();
                    }else{
                        dialogNoAssessSubmit();
                    }
                }

            }
        });

        /*
        * 更多功能按钮菜单相关信息
        * */
        mSbtnMore = (ScaleButton) findViewById(R.id.sbtn_more);
        mSbtnMore.setVisibility(View.INVISIBLE);
        mSbtnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdqh!=null) {
                    initPopupWindowMoreFunction();
                }else {
                    Toast.makeText(getApplicationContext(),"数据加载中，请稍后重试...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        /*
        * 计时器显示
        * */
        mSbtnTimeMeter = (ScaleButton) findViewById(R.id.sbtn_timeMeter);
        mSbtnTimeMeter.setVisibility(View.INVISIBLE);

        mVp = (ViewPager) findViewById(R.id.viewpager);



    }

    /*********************
     * ******************
     *实现试卷明细解析
     * *****************
     ******************/
    /************************************************************************************************************************/

    @Override
    public void loadPaperData(WeekAscensionPaperEntity data) {

        mEntityRdqh =data;

        int AnswerState = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState();

        if(AnswerState!=0) {
            int sumQuesChild = mEntityRdqh.getModelItemAnswerDetailList().size();
            for(int i=0;i<sumQuesChild;i++){
                int sumQuesSubChild = mEntityRdqh.getModelItemAnswerDetailList().get(i).getModelQuesSubChildAnswerList().size();
                for(int j=0;j<sumQuesSubChild;j++){
                    /*
                    * 赋值学生答案
                    * */
                    mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().
                            get(j).getSubChildList().get(0).setSubChildStuAnswer(mEntityRdqh.getModelItemAnswerDetailList().get(i).
                            getModelQuesSubChildAnswerList().get(j).getModelQuesChildAnswerList().get(0).getAnswer());
                    /*
                    * 赋值学生自评
                    * */
                    mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().
                            get(j).getSubChildList().get(0).setSubChildStuAssess(mEntityRdqh.getModelItemAnswerDetailList().get(i).
                            getModelQuesSubChildAnswerList().get(j).getModelQuesChildAnswerList().get(0).getStuAssess());

                    /*
                    * 赋值字面作答图片
                    * */
                    mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().
                            get(j).getSubChildList().get(0).setUpLoadPath(mEntityRdqh.getModelItemAnswerDetailList().get(i).
                            getModelQuesSubChildAnswerList().get(j).getModelQuesChildAnswerList().get(0).getUpLoadPath());

                }
            }
        }


        //这里因为是3.0一下版本，所以需继承FragmentActivity，通过getSupportFragmentManager()获取FragmentManager
        //3.0及其以上版本，只需继承Activity，通过getFragmentManager获取事物
        FragmentManager fm = getSupportFragmentManager();
        //初始化自定义适配器MyFragmentPageAdapter
        mAdapter =  new WeekAscensionPaperFragmentAdapter(fm);
        MyOnPageChangeListener myOnPageChangeListener = new MyOnPageChangeListener();
        mVp.setOnPageChangeListener(myOnPageChangeListener);
        //绑定自定义适配器
//        if(AnswerState==2||AnswerState==3){
//            mAdapter.clearFragmentsCache();
//        }
        mAdapter.clearFragmentsCache();


        mVp.setAdapter(mAdapter);

        /*
        * 若为非已提交状态显示时间并开启计时功能，若为已提交状态则只显示已学习时长
        * */
        LastTimer = data.getModelSinglePaperInfo().getModelPaperInfo().getDuration();//获取已作答时长

        if(AnswerState==0) {
            handler.postDelayed(runnable, 1000);
            mSbtnSubmit.setText("提交");
            mSbtnSubmit.setTextColor(this.getResources().getColor(R.color.gray));
        } else if(AnswerState==1){
            handler.postDelayed(runnable, 1000);
            mSbtnSubmit.setText("提交");
            mSbtnSubmit.setTextColor(this.getResources().getColor(R.color.white));
        } else if(AnswerState==2){
            mSbtnTimeMeter.setText(getStringTime(LastTimer));
            mSbtnSubmit.setText("完成");
            mSbtnSubmit.setTextColor(this.getResources().getColor(R.color.white));
        } else if(AnswerState==3){
            mSbtnTimeMeter.setText(getStringTime(LastTimer));
        }

        if(mEntityRdqh!=null){
            mSbtnAnswerSheet.setVisibility(View.VISIBLE);
            mSbtnMore.setVisibility(View.VISIBLE);
            mSbtnTimeMeter.setVisibility(View.VISIBLE);
            if(AnswerState==3){
                mSbtnSubmit.clearAnimation();
                mSbtnSubmit.setVisibility(View.INVISIBLE);
            }else{
                mSbtnSubmit.setVisibility(View.VISIBLE);
            }
        }

        if(AnswerState==3&IsSubmitSuccess){
            saveDiagnosticReport();
        }

    }


    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {
        IsSubmitSuccess = true;
        updateViews(true);
    }

    @Override
    public void openAssessDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {
        mLoadingDialog.dismiss();
//        if (isSucceed){
//            ToastUtils.showShort("提交成功");
//        }else {
//            ToastUtils.showShort("提交失败");
//        }
    }

    @Override
    public void updatingReportResult(boolean isReportSucceed) {
        if(isReportSucceed){
            ToastUtils.showShort("诊断报告提交成功");
            Fragment fragment = (Fragment) ((WeekAscensionPaperFragmentAdapter) mVp.getAdapter()).instantiateItem(mVp,mVp.getCurrentItem());
            ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
            mAnswerSheet = new AnswerSheet(WeekAscensionPaperActivity.this,mVp.getCurrentItem(),childViewPage.getCurrentItem(),ZnbkPaperDef.FROM_WEEK_ASCENSION);
            mAnswerSheet.setClippingEnabled(false);//使popupwindow显示为全屏
            mAnswerSheet.showAtLocation(WeekAscensionPaperActivity.this.findViewById(R.id.main), Gravity.TOP, 0, 0);

        }else{
            ToastUtils.showShort("诊断报告提交失败");
        }
    }

    public  LoadingDialog getLoadingDialog(){
        return mLoadingDialog;
    }

    @Override
    public RxAppCompatActivity getHolderActivity() {
        return null;
    }


    /************************************************************************************************************************/
    /*
    * LazyViewPage切换事件监听
    * */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {

            /*
            * 绑定当前题目小页码
            * */
            lastBigViewPage = currentBigViewPage;

            /*
            * 获取试卷明细相关信息
            * */
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
//            if(mPaperJsonXtfx.getModelPaperInfo().getAnswerState()!=2) {
////                slideSave(lastBigViewPage, false);
//            }
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            /*************************************************************************************************************************/
            currentBigViewPage = arg0;
            Log.e("=======bigViewPage====","===AA==="+currentBigViewPage);

            /*
            * 隐藏软键盘
            * */
            HideKeyboard();

        }

    }


    //隐藏虚拟键盘:Fragment进行切换的时候使用
    public  void HideKeyboard() {
        /**隐藏软键盘**/
        View viewK = this.getWindow().peekDecorView();
        if(viewK != null){
            InputMethodManager inputmanger = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(viewK.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
    * 监听系统home事件
    * */
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        System.out.println("onUserLeaveHint");
    }

    /*
    * 监听系统返回事件
    * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if(mEntityRdqh!=null) {
                if (mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState() != 3) {
                    saveAndSubmitPaper(false, false);
                }else{
                    finish();
                }
            }
            return false;
        }
        return false;
    }



    /******************************************更多功能popupwindow****************************************************/

    private PopupWindowMoreFunction mPopupWindowMoreFunction;
    private void initPopupWindowMoreFunction(){
        if (mPopupWindowMoreFunction == null) {
            //自定义的单击事件
            OnClickLintener paramOnClickListener = new OnClickLintener();
            mPopupWindowMoreFunction = new PopupWindowMoreFunction(this, paramOnClickListener, Control.dip2px(this,140), Control.dip2px(this,80));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            mPopupWindowMoreFunction.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        mPopupWindowMoreFunction.dismiss();
                    }
                }
            });
        }


        //显示当前试题的收藏情况
        if(!mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).isIsLike()) {
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
        }else if(mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).isIsLike()){
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
        }

        //设置默认获取焦点
        mPopupWindowMoreFunction.setFocusable(true);
        //以某个控件的x和y的偏移量位置开始显示窗口
        mPopupWindowMoreFunction.showAsDropDown(mSbtnMore, Control.dip2px(this,-120), Control.dip2px(this,15));
        //如果窗口存在，则更新
        mPopupWindowMoreFunction.update();
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_dictionary:
                    System.out.println("=======电子词典=========");
                    mPopupWindowMoreFunction.dismiss();
                    startActivity(new Intent(getApplicationContext(), DictionaryActicity.class));
                    break;
                case R.id.layout_difficult_question:
                    System.out.println("=======收藏与否=========");
                    int CollectionFlag = -1;
                    if(!mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).isIsLike()) {
                        CollectionFlag = 1;
                        mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).setIsLike(true);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
                    }else if(mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).isIsLike()){
                        CollectionFlag = 0;
                        mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).setIsLike(false);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
                    }
                    String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getQuesID();

                    String Theme = "";
                    if(!mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getQuesBrief().equals("")){
                        Theme = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getQuesBrief();
                    }else{
                        if(!mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).
                                getChildList().get(0).getChildAsk().equals("")){
                            Theme = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).
                                    getChildList().get(0).getChildAsk();
                        }else{
                            Theme = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).
                                    getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                        }
                    }
                    String GenreID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getGenreID();
                    String TypeNo = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getTypeNo();
                    String ResType = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(currentBigViewPage).getResType();
                    if(ResType.equals("Q")){
                        ResType =  TypeNo;
                    }

                    ZnbkPaperScInfor.changeCollectionEntityModel =  new ChangeCollectionEntityModel(CollectionFlag,
                            GenreID,QuesID,ResType, UserInfo.StageNo, UserInfo.StuId,UserInfo.SubjectId,Theme,TypeNo);

                    changeCollection();
                    break;

                default:
                    break;
            }

        }

    }
    /*
    * 加入收藏、取消收藏
    * */
    ChangeCollectionPresenter mChangeCollectionPresenter;
    private void changeCollection(){
        mChangeCollectionPresenter = new ChangeCollectionPresenter(this,mQuesOrPaperFrom);
        mChangeCollectionPresenter.getData(false);
    }
    /********************************************************************************************************************/



  /*
    * 提交dialog 有自评
    * */
    public void dialogAssessSubmit() {
        final ZnbkDialogSubmit mZnbkDialogSubmit = new ZnbkDialogSubmit(this,mQuesOrPaperFrom);
        mZnbkDialogSubmit.getWindow().setWindowAnimations(R.style.Dialog_Anim_Style);
        mZnbkDialogSubmit.show();
        mZnbkDialogSubmit.setClicklistener(new ZnbkDialogSubmit.ClickListenerInterface() {

            @Override
            public void doGoAnswer() {
                //关闭弹窗
                mZnbkDialogSubmit.dismiss();
            }

            @Override
            public void doSubmit() {
                handler.removeCallbacks(runnable);
                //关闭弹窗
                mZnbkDialogSubmit.dismiss();
                if (mLoadingDialog == null) {
                    LoadingDialog.Builder builder1=new LoadingDialog.Builder(WeekAscensionPaperActivity.this)
                            .setMessage(getString(R.string.updateing))
                            .setCancelOutside(false);
                    mLoadingDialog =builder1.create();
                    mLoadingDialog.show();
                }else{
                    mLoadingDialog.show();
                }

                mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().setAnswerState(3);
                saveAndSubmitPaper(true,false);
            }

            @Override
            public void doAssessSubmit() {
                //自评再提交
                mZnbkDialogSubmit.dismiss();
                if (mLoadingDialog == null) {
                    LoadingDialog.Builder builder1=new LoadingDialog.Builder(WeekAscensionPaperActivity.this)
                            .setMessage(getString(R.string.updateing))
                            .setCancelOutside(false);
                    mLoadingDialog =builder1.create();
                    mLoadingDialog.show();
                }else{
                    mLoadingDialog.show();
                }
                mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().setAnswerState(2);
                saveAndSubmitPaper(true,true);
            }

        });
    }

    /*
    * 提交dialog 无自评
    * */
    public void dialogNoAssessSubmit() {
        final ZnbkDialogNoAssessSubmit mZnbkDialogNoAssessSubmit = new ZnbkDialogNoAssessSubmit(this,mQuesOrPaperFrom);
        mZnbkDialogNoAssessSubmit.getWindow().setWindowAnimations(R.style.Dialog_Anim_Style);
        mZnbkDialogNoAssessSubmit.show();
        mZnbkDialogNoAssessSubmit.setClicklistener(new ZnbkDialogNoAssessSubmit.ClickListenerInterface() {

            @Override
            public void doGoAnswer() {
                //关闭弹窗
                mZnbkDialogNoAssessSubmit.dismiss();
            }

            @Override
            public void doSubmit() {
                handler.removeCallbacks(runnable);
                //关闭弹窗
                mZnbkDialogNoAssessSubmit.dismiss();
                if (mLoadingDialog == null) {
                    LoadingDialog.Builder builder1=new LoadingDialog.Builder(WeekAscensionPaperActivity.this)
                            .setMessage(getString(R.string.updateing))
                            .setCancelOutside(false);
                    mLoadingDialog =builder1.create();
                    mLoadingDialog.show();
                }else{
                    mLoadingDialog.show();
                }
                mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().setAnswerState(3);
                saveAndSubmitPaper(true,false);
            }

        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        if (bottom > oldBottom){
            //输入法软键盘关闭
            Log.d(">>>>>>>>>crg", "输入法软键盘关闭: ");
        } else if (bottom < oldBottom){
            //输入法软键盘打开
            Log.d(">>>>>>>>>crg", "输入法软键盘打开: ");
        }

    }


    /*******************************************************************************************************************************/
    /*******************************************************************************************************************************/
    /*******************************************************************************************************************************/

    /*
    * 保存提交试卷作答
    * */
    SaveWeekAscensionPaperPresenter mSaveWeekAscensionPaperPresenter;
    private void saveSingleQues(boolean isFromExit,boolean isAssess){
        mSaveWeekAscensionPaperPresenter = new SaveWeekAscensionPaperPresenter(this,mQuesOrPaperFrom);
        mSaveWeekAscensionPaperPresenter.getData(false,isFromExit,isAssess);
    }

    /*
    * 保存提交试卷作答-->组装提交json
    * */
    private void saveAndSubmitPaper(boolean isFromExit,boolean isAssess){

        int BigAnsweredItemCount = 0;

//       List<SaveSystemReviewPaperEntity> SaveSystemReviewPaperEntity =new ArrayList<SaveSystemReviewPaperEntity>();

        List<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean> ModelItemAnswerDetailListBean
                =new ArrayList<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean>();
        int sumItemAnswerDetailList = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getTotalItemCount();

        for(int i=0;i<sumItemAnswerDetailList;i++){

            List<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean.ModelQuesSubChildAnswerListBean> ModelQuesSubChildAnswerListBean
                    =new ArrayList<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean.ModelQuesSubChildAnswerListBean>();
            int sumQuesChildAnswerList = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().size();

            for(int j=0;j<sumQuesChildAnswerList;j++) {
                List<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean.ModelQuesSubChildAnswerListBean.ModelQuesChildAnswerListBean> ModelQuesChildAnswerListBean
                        = new ArrayList<SaveWeekAscensionPaperEntity.ModelItemAnswerDetailListBean.ModelQuesSubChildAnswerListBean.ModelQuesChildAnswerListBean>();
                int sumQuesSubChildAnswerList = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().get(j).getSubChildList().size();

                for (int k = 0; k < sumQuesSubChildAnswerList; k++) {
                    String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(j).getSubChildList().get(k).getUpLoadPath();
                    String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(j).getSubChildList().get(k).getSubChildStuAssess();
                    String Answer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(j).getSubChildList().get(k).getSubChildStuAnswer();

                    ModelQuesChildAnswerListBean.add(SaveWeekAscensionPaperEntityModel.getModelQuesChildAnswerListBean(1, UpLoadPath, StuAssess, Answer));
                    ModelQuesSubChildAnswerListBean.add(SaveWeekAscensionPaperEntityModel.getModelQuesSubChildAnswerListBean(ModelQuesChildAnswerListBean, k + 1));
                }
            }

            String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getQuesID();
            int TotalItemCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getTotalItemCount();
            int ChildIntemCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getChildList().size();
            int AnsweredItemCount = 0;
            int AnsweredItemCountTrue = 0;
            if(TotalItemCount==ChildIntemCount){
                for(int m=0;m<TotalItemCount;m++){
                    String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getUpLoadPath();
                    String Answer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getSubChildAnswer();
                    String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getSubChildStuAnswer();
                    String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getSubChildStuAssess();
                    if(!StuAnswer.equals("")||!StuAssess.equals("")||!UpLoadPath.equals("")){
                        AnsweredItemCount++;
                        if(Answer.equals(StuAnswer)||StuAssess.equals("优秀")||StuAssess.equals("一般")||StuAssess.equals("合格")){
                            AnsweredItemCountTrue++;
                        }
                    }
                }
            }else if(TotalItemCount>ChildIntemCount){
                String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                String Answer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getSubChildAnswer();
                String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getSubChildStuAnswer();
                String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getSubChildStuAssess();
                if(StuAssess.equals("")&UpLoadPath.equals("")){
                    if(!StuAnswer.equals("")){
                        for(int p=0;p<TotalItemCount;p++){
                            if(!Control.returnArray(StuAnswer,"$、",2)[p].equals("")){
                                AnsweredItemCount++;
                                if(Control.returnArray(StuAnswer,"$、",2)[p].equals(Control.returnArray(Answer,"$、",2)[p])){
                                    AnsweredItemCountTrue++;
                                }
                            }
                        }
                    }

                }else{
                    AnsweredItemCount = TotalItemCount;
                    if(StuAssess.equals("优秀")||StuAssess.equals("一般")||StuAssess.equals("合格")){
                        AnsweredItemCountTrue++;
                    }
                }
            }

            if(AnsweredItemCount==TotalItemCount){
                BigAnsweredItemCount++;
            }

            int AnswerState = -1;
            if(TotalItemCount==ChildIntemCount){
                for(int m=0;m<TotalItemCount;m++){
                    String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getUpLoadPath();
                    String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getSubChildStuAnswer();
                    String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                            getChildList().get(m).getSubChildList().get(0).getSubChildStuAssess();
                    if(StuAnswer.equals("")&StuAssess.equals("")&UpLoadPath.equals("")){
                        AnswerState = 0;
                    }else{
                        AnswerState = 2;
                    }
                }
            }else if(TotalItemCount>ChildIntemCount){
                String UpLoadPath = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                String StuAnswer = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getSubChildStuAnswer();
                String StuAssess = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).
                        getChildList().get(0).getSubChildList().get(0).getSubChildStuAssess();

                if(StuAnswer.equals("")&StuAssess.equals("")&UpLoadPath.equals("")){
                    AnswerState = 0;
                }else{
                    for(int p=0;p<TotalItemCount;p++){
                        if(Control.returnArray(StuAnswer,"$、",2)[p].equals("")){
                            AnswerState = 1;
                            break;
                        }else{
                            AnswerState = 2;
                        }
                    }
                }
            }

            int Duration = paperTimeLong;

            String PaperID = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getPaperID();

            double CorrectRate = Control.getCorrectRate(AnsweredItemCountTrue,TotalItemCount);

            String StuID = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getStuID();

            String CreatTime = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getCreateTime();

            int QuesFrom = 1;

            ModelItemAnswerDetailListBean.add(SaveWeekAscensionPaperEntityModel.getModelItemAnswerDetailListBean(QuesID,AnsweredItemCount,AnswerState,
                    Duration,PaperID,CorrectRate,TotalItemCount,StuID,CreatTime,QuesFrom,ModelQuesSubChildAnswerListBean));

        }

        ZnbkPaperRdqhInfor.ModelItemAnswerDetailListBean = ModelItemAnswerDetailListBean;

        ZnbkPaperRdqhInfor.AnsweredItemCount = BigAnsweredItemCount;

        ZnbkPaperRdqhInfor.AnswerState = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState();

        ZnbkPaperRdqhInfor.Duration = paperTimeLong;

        ZnbkPaperRdqhInfor.PaperName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getPaperName();

        saveSingleQues(isFromExit,isAssess);//答案不同或自评不同就保存作答结果

    }


    /*
    * 保存提交练习报告
    * */
    SaveDiagnosticReportPresenter mSaveDiagnosticReportPresenter;
    private void saveQuesReport(){
        mSaveDiagnosticReportPresenter = new SaveDiagnosticReportPresenter(this,mQuesOrPaperFrom);
        mSaveDiagnosticReportPresenter.getData(false);
    }

    /*
    * 保存练习报告
    * */
    private void saveDiagnosticReport(){
        List<SaveDiagnosticReportEntity.ModelDiagnosticReportParamListBean> ModelDiagnosticReportParamListBean
                = new ArrayList<SaveDiagnosticReportEntity.ModelDiagnosticReportParamListBean>();

        int sumKnowledgeList = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().size();
        Log.e("sumKnowledgeList","======="+sumKnowledgeList);
        ArrayList<String> ArrayKnowledgeName = new ArrayList<>();
        for(int i=0;i<sumKnowledgeList;i++){
            String KnowledgeName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(i).getKnowledgeName();
            ArrayKnowledgeName.add(KnowledgeName);
        }
        Log.e("ArrayKnowledgeName","======="+ArrayKnowledgeName);
        int sumImportantZSDList = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().size();
        for(int j=0;j<sumImportantZSDList;j++){

            int sumKlgList = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(j).getImportantZSD().size();
            List<SaveDiagnosticReportEntity.ModelDiagnosticReportParamListBean.KlgListBean> KlgListBean = new ArrayList<SaveDiagnosticReportEntity.ModelDiagnosticReportParamListBean.KlgListBean>();
            for(int k =0;k<sumKlgList;k++) {
                String ZSDName = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(j).getImportantZSD().get(k).getZSDName();
                Log.e("contains","===iiii===="+k+"======="+ArrayKnowledgeName.contains(ZSDName));
                if(ArrayKnowledgeName.contains(ZSDName)){
                    for(int p=0;p<sumKnowledgeList;p++){
                        if(ArrayKnowledgeName.get(p).equals(ZSDName)){

                            String LaseCcore = "0";
                            String RequiredScore = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(p).getAvalidScore();
                            String KnowledgeName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(p).getKnowledgeName();
                            String OriginalScore = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(p).getBasicScore();
                            String ZSDNO = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(p).getZSDNO();

                            KlgListBean.add(SaveDiagnosticReportEntityModel.getKlgListBean(LaseCcore, RequiredScore,
                                    KnowledgeName, OriginalScore, ZSDNO));

                        }
                    }

                }
            }

            String QuesID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(j).getQuesID();
            String SubjectId = UserInfo.BaseSubjectID;
            String GenreID = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(j).getGenreID();
            double CorrectRate = mEntityRdqh.getModelItemAnswerDetailList().get(j).getCorrectRate();
            int IsRight = -1;
            if(CorrectRate<0.6){
                IsRight = 0;
            }else{
                IsRight = 1;
            }
            String TypeNo = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(j).getTypeNo();

            ModelDiagnosticReportParamListBean.add(SaveDiagnosticReportEntityModel.getModelDiagnosticReportParamListBean(QuesID,
                    SubjectId,GenreID,IsRight, TypeNo,KlgListBean ));

        }
        ZnbkPaperRdqhInfor.ModelDiagnosticReportParamListBean = ModelDiagnosticReportParamListBean;


        List<SaveDiagnosticReportEntity.ModelDiagnosticReportListBean> ModelDiagnosticReportListBean
                = new ArrayList<SaveDiagnosticReportEntity.ModelDiagnosticReportListBean>();


        String UpdateTime = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getUpdateTime();
        String PaperId = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getPaperID();
        String StuId = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getStuID();
        int PaperFrom = 1;
        int Duration = paperTimeLong;
        String CreateTime = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getCreateTime();
        int TotalItemCount = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getTotalItemCount();

        /*
        * 大题自评正确的个数： AssessRightItemCount
        * */
        int sumAssessRightItemCount = 0;
        for(int i=0;i<TotalItemCount;i++){
            double CorrectRate = mEntityRdqh.getModelItemAnswerDetailList().get(i).getCorrectRate();
            if(CorrectRate>0.6){
                int smallTotalItemCount = mEntityRdqh.getModelItemAnswerDetailList().get(i).getModelQuesSubChildAnswerList().size();
                int smallStuAssessRight = 0;
                for(int j=0;j<smallTotalItemCount;j++){
                    String smallStuAssess = mEntityRdqh.getModelItemAnswerDetailList().get(i).getModelQuesSubChildAnswerList().get(j).
                            getModelQuesChildAnswerList().get(0).getStuAssess();
                    if(smallStuAssess.equals("优秀")||smallStuAssess.equals("一般")||smallStuAssess.equals("一般")){
                        smallStuAssessRight++;
                    }
                }
                if(smallStuAssessRight*2>smallTotalItemCount){
                    sumAssessRightItemCount++;
                }
            }
        }
        int AssessRightItemCount = sumAssessRightItemCount;

        /*
        * 试卷准确率： PaperAnswerRate
        * */
        int sumAnswerdTrue = 0;
        for(int i=0;i<TotalItemCount;i++){
            if(mEntityRdqh.getModelItemAnswerDetailList().get(i).getCorrectRate()>0.6){
                sumAnswerdTrue++;
            }
        }
        int PaperAnswerRate = (int) Control.getCorrectRate(sumAnswerdTrue,TotalItemCount)*100;

        /*
        * 大题未完全作答的个数：NotAnsweredItemCount
        * */
        int NotAllAnsweredItemCount = 0;
        for(int i=0;i<TotalItemCount;i++){
            int sumTotalItemCount = mEntityRdqh.getModelItemAnswerDetailList().get(i).getTotalItemCount();
            int sumAnsweredItemCount = mEntityRdqh.getModelItemAnswerDetailList().get(i).getAnsweredItemCount();
            if(sumTotalItemCount!=sumAnsweredItemCount){
                NotAllAnsweredItemCount++;
            }
        }

        /*
        * 答错的大题个数：WrongItemCount
        * 答对的大题个数：RightItemCount
        * */
        int WrongItemCount = 0;
        for(int i=0;i<TotalItemCount;i++){
            double correctRate = mEntityRdqh.getModelItemAnswerDetailList().get(i).getCorrectRate();
            if(correctRate<0.6){
                WrongItemCount++;
            }
        }
        int RightItemCount = TotalItemCount-WrongItemCount;

        /*
        * 学科ID：SubjectId
        * 年级ID：StageNo
        * */
        String SubjectId = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getSubjectID();
        String StageNo = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getStageNo();

        List<?> Knowledges = new ArrayList<>();

        ModelDiagnosticReportListBean.add(SaveDiagnosticReportEntityModel.getModelDiagnosticReportListBean(AssessRightItemCount,
                UpdateTime,PaperId,StuId,PaperFrom,Duration, CreateTime, PaperAnswerRate,NotAllAnsweredItemCount,TotalItemCount,
                WrongItemCount,SubjectId,StageNo,RightItemCount,Knowledges));

        ZnbkPaperRdqhInfor.ModelDiagnosticReportListBean = ModelDiagnosticReportListBean;

        saveQuesReport();

    }

}